package com.mazaiting.web.converter;

import com.mazaiting.common.core.domain.result.ResultCode;
import com.mazaiting.common.core.enums.IBaseEnum;
import com.mazaiting.common.core.ex.runtime.ValidationException;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.lang.NonNull;

/**
 * 字符串转换为自定义枚举值工厂 - 需要在 WebMvcConfigurer.addFormatters()中注册
 * 1. Spring 默认使用 StringToEnumConverterFactory
 * @see org.springframework.core.convert.support.StringToEnumConverterFactory
 * 2. 默认查找方法
 * @see org.springframework.core.convert.support.GenericConversionService.Converters#find(org.springframework.core.convert.TypeDescriptor, org.springframework.core.convert.TypeDescriptor)
 *
 * @author mazaiting
 * @create_time 2022/10/1 00:30
 */
public class String2IBaseEnumConverterFactory implements ConverterFactory<String, IBaseEnum<?>> {

    @Override
    @NonNull
    public <T extends IBaseEnum<?>> Converter<String, T> getConverter(@NonNull Class<T> targetType) {
        // 获取全部的枚举常量
        T[] enums = targetType.getEnumConstants();
        // 转换
        return source -> {
            // 遍历
            for (T e : enums) {
                // 判断值是否相等
                if (String.valueOf(e.getValue()).equals(source)) {
                    return e;
                }
            }
            // 异常信息
            String message = targetType.getSimpleName() + "中不存在枚举值:【" + source + "】";
            // 抛出自定义异常, 在全局异常处理中获取异常信息
            throw new ValidationException(ResultCode.PARAM_CHECK_ENUM_ERROR.getCode(), message);
        };
    }
}
